﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using UnityEngine.Networking;


namespace xuni
{


    public static class HttpUtils
    {

        public static string GetLastSegment(string url)
        {
            var uri = new Uri(url);
            var segments = uri.Segments;
            return segments[segments.Length - 1];
        }


        public static string AddTimeStamp(string url)
        {
            var index = url.LastIndexOf('?');
            if (index >= 0)
            {
                return StringUtils.Builder.Append(url)
                    .Append('&').Append("t=").Append(DateTime.Now.Ticks / 10000)
                    .BuildString();
            }

            return StringUtils.Builder.Append(url)
                    .Append("?t=").Append(DateTime.Now.Ticks / 10000)
                    .BuildString();
        }


        public static string BuildGetUrl(string url, List<KeyValuePair<string, string>> reqParams)
        {
            var sb = StringUtils.Builder;

            //=====生成签名
            reqParams.Sort(HttpUtils.SortByKeyCmp);

            for (var i = 0; i < reqParams.Count; ++i)
            {
                sb.Append(reqParams[i].Value);
            }
            var text = sb.Append("57EJqwo7wsLL4c79").BuildString();
            //Debug.Log($"sign: {text}");

            var signMd5 = MD5Utils.StringMD5(text, MD5.Create());
            reqParams.Add(new KeyValuePair<string, string>("sign", signMd5));
            reqParams.Add(new KeyValuePair<string, string>("signType", "md5"));

            //=====生成url
            if (!string.IsNullOrEmpty(url))
                sb.Append(url);

            for (var i = 0; i < reqParams.Count; ++i)
            {
                var kv = reqParams[i];
                if (0 == i)
                    sb.Append('?').Append(kv.Key).Append('=').Append(UnityWebRequest.EscapeURL(kv.Value, Encoding.UTF8));
                else
                    sb.Append('&').Append(kv.Key).Append('=').Append(UnityWebRequest.EscapeURL(kv.Value, Encoding.UTF8));
            }

            /*
            if (addTimeStamp && sb.Length > url.Length)
            {
                sb.Append('&').Append("t=").Append(DateTime.Now.Ticks / 10000);
            }
            */

            return sb.BuildString();
        }

        
        public static int SortByKeyCmp(KeyValuePair<string, string> a, KeyValuePair<string, string> b)
        {
            if (string.IsNullOrEmpty(a.Key))
            {
                if (string.IsNullOrEmpty(b.Key))
                    return -1;
                return 1;
            }

            if (string.IsNullOrEmpty(b.Key))
                return -1;

            return a.Key.CompareTo(b.Key);
        }



    } //end of class


}
